/**
 * amis v6.13.0
 * build time: 2025-08-12
 * Copyright 2018-2025 baidu
 */

import { __extends, __assign, __decorate, __metadata } from 'tslib';
import React from 'react';
import inRange from 'lodash/inRange';
import { getVariable, createObject, hasAbility, columnsSplit, flattenTreeWithLeafNodes, formateCheckThemeCss, setThemeClassName, CustomStyle, autobind, OptionsControl } from 'amis-core';
import { Checkbox, TooltipWrapper, Icon, Spinner } from 'amis-ui';
import { supportStatic } from './StaticHoc.js';
import debounce from 'lodash/debounce';

var CheckboxesControl = /** @class */ (function (_super) {
    __extends(CheckboxesControl, _super);
    function CheckboxesControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.checkboxRef = React.createRef();
        _this.childRefs = [];
        return _this;
    }
    CheckboxesControl.prototype.doAction = function (action, data, throwErrors) {
        var _a, _b;
        var _c = this.props, resetValue = _c.resetValue, onChange = _c.onChange, formStore = _c.formStore, store = _c.store, name = _c.name;
        var actionType = action === null || action === void 0 ? void 0 : action.actionType;
        if (actionType === 'clear') {
            onChange('');
        }
        else if (actionType === 'reset') {
            var pristineVal = (_b = getVariable((_a = formStore === null || formStore === void 0 ? void 0 : formStore.pristine) !== null && _a !== void 0 ? _a : store === null || store === void 0 ? void 0 : store.pristine, name)) !== null && _b !== void 0 ? _b : resetValue;
            onChange(pristineVal !== null && pristineVal !== void 0 ? pristineVal : '');
        }
    };
    CheckboxesControl.prototype.reload = function (subpath, query) {
        var reload = this.props.reloadOptions;
        reload && reload(subpath, query);
    };
    CheckboxesControl.prototype.handleAddClick = function () {
        var onAdd = this.props.onAdd;
        onAdd && onAdd();
    };
    CheckboxesControl.prototype.handleEditClick = function (e, item) {
        var onEdit = this.props.onEdit;
        e.preventDefault();
        e.stopPropagation();
        onEdit && onEdit(item);
    };
    CheckboxesControl.prototype.handleDeleteClick = function (e, item) {
        var onDelete = this.props.onDelete;
        e.preventDefault();
        e.stopPropagation();
        onDelete && onDelete(item);
    };
    CheckboxesControl.prototype.componentDidMount = function () {
        this.updateBorderStyle();
        var updateBorderStyleFn = debounce(this.updateBorderStyle, 100);
        if (this.checkboxRef.current) {
            // 监听容器宽度变化，更新边框样式
            this.checkboxRefObserver = new ResizeObserver(updateBorderStyleFn);
            this.checkboxRefObserver.observe(this.checkboxRef.current);
        }
    };
    CheckboxesControl.prototype.componentWillUnmount = function () {
        var _a;
        (_a = this.checkboxRefObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
    };
    CheckboxesControl.prototype.updateBorderStyle = function () {
        if (this.props.optionType !== 'button') {
            return;
        }
        if (!this.childRefs.length) {
            return;
        }
        var children = this.childRefs.map(function (item) { return item === null || item === void 0 ? void 0 : item.ref; });
        var lastOffsetTop = children[0].labelRef.current.offsetTop;
        var options = [];
        var len = children.length;
        options[0] = 'first';
        var lastLineStart = 0;
        for (var i = 1; i < len; i++) {
            var item = children[i];
            // 如果当前元素的 offsetTop 与上一个元素的 offsetTop 不同，则说明是新的一行
            var currentOffsetTop = item.labelRef.current.offsetTop;
            options[i] = '';
            if (currentOffsetTop !== lastOffsetTop) {
                options[i] = 'first';
                options[i - 1] += ' last';
                lastLineStart = i;
                lastOffsetTop = currentOffsetTop;
            }
        }
        options[len - 1] += ' last';
        options.forEach(function (option, index) {
            if (index >= lastLineStart) {
                option += ' last-line';
            }
            children[index].setClassName(option);
        });
    };
    CheckboxesControl.prototype.renderGroup = function (option, index) {
        var _this = this;
        var _a;
        var _b = this.props, cx = _b.classnames, labelField = _b.labelField;
        if (!((_a = option.children) === null || _a === void 0 ? void 0 : _a.length)) {
            return null;
        }
        var children = option.children.map(function (option, index) {
            return _this.renderItem(option, index);
        });
        var body = this.columnsSplit(children);
        return (React.createElement("div", { key: 'group-' + index, className: cx('CheckboxesControl-group', option.className) },
            React.createElement("label", { className: cx('CheckboxesControl-groupLabel', option.labelClassName) }, option[labelField || 'label']),
            body));
    };
    CheckboxesControl.prototype.addChildRefs = function (el) {
        el && this.childRefs.push(el);
    };
    CheckboxesControl.prototype.renderItem = function (option, index) {
        var _this = this;
        var _a;
        if ((_a = option.children) === null || _a === void 0 ? void 0 : _a.length) {
            return this.renderGroup(option, index);
        }
        var _b = this.props, render = _b.render, itemClassName = _b.itemClassName, onToggle = _b.onToggle, selectedOptions = _b.selectedOptions, disabled = _b.disabled, inline = _b.inline, labelClassName = _b.labelClassName, labelField = _b.labelField, removable = _b.removable, editable = _b.editable, __ = _b.translate, optionType = _b.optionType, menuTpl = _b.menuTpl, data = _b.data, cx = _b.classnames, testIdBuilder = _b.testIdBuilder;
        var labelText = String(option[labelField || 'label']);
        var optionLabelClassName = option['labelClassName'];
        var itemTestIdBuilder = testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('item-' + labelText || index);
        var finalDisabled = disabled || option.disabled;
        return (React.createElement(Checkbox, { className: itemClassName, key: index, onChange: function () { return onToggle(option); }, checked: !!~selectedOptions.indexOf(option), disabled: finalDisabled, inline: inline, labelClassName: optionLabelClassName || labelClassName, description: option.description, optionType: optionType, testIdBuilder: itemTestIdBuilder, ref: this.addChildRefs },
            menuTpl
                ? render("checkboxes/".concat(index), menuTpl, {
                    data: createObject(data, option)
                })
                : labelText,
            option.disabledTip && finalDisabled ? (React.createElement(TooltipWrapper, { placement: "right", tooltip: option.disabledTip, trigger: "hover" },
                React.createElement("a", { className: cx('Select-option-disabledTip') },
                    React.createElement(Icon, { className: "icon", icon: "question2" })))) : null,
            removable && hasAbility(option, 'removable') ? (React.createElement("a", { "data-tooltip": __('Select.clear'), "data-position": "left" },
                React.createElement(Icon, { icon: "minus", className: "icon", onClick: function (e) { return _this.handleDeleteClick(e, option); } }))) : null,
            editable && hasAbility(option, 'editable') ? (React.createElement("a", { "data-tooltip": "\u7F16\u8F91", "data-position": "left" },
                React.createElement(Icon, { icon: "pencil", className: "icon", onClick: function (e) { return _this.handleEditClick(e, option); } }))) : null));
    };
    CheckboxesControl.prototype.columnsSplit = function (body) {
        var _a = this.props, columnsCount = _a.columnsCount, cx = _a.classnames;
        var result = [];
        var tmp = [];
        body.forEach(function (node) {
            // 如果有分组，组内单独分列
            if (node && node.key && String(node.key).startsWith('group')) {
                // 夹杂在分组间的无分组选项，分别成块
                if (tmp.length) {
                    result.push(columnsSplit(tmp, cx, columnsCount));
                    tmp = [];
                }
                result.push(node);
            }
            else {
                tmp.push(node);
            }
        });
        // 收尾
        tmp.length && result.push(columnsSplit(tmp, cx, columnsCount));
        return result;
    };
    CheckboxesControl.prototype.render = function () {
        var _this = this;
        var _a = this.props, className = _a.className, style = _a.style, disabled = _a.disabled, placeholder = _a.placeholder, options = _a.options, inline = _a.inline, columnsCount = _a.columnsCount, selectedOptions = _a.selectedOptions, onToggle = _a.onToggle, onToggleAll = _a.onToggleAll, checkAll = _a.checkAll, checkAllText = _a.checkAllText, cx = _a.classnames, itemClassName = _a.itemClassName, labelClassName = _a.labelClassName, creatable = _a.creatable, addApi = _a.addApi, createBtnLabel = _a.createBtnLabel, __ = _a.translate, optionType = _a.optionType, loading = _a.loading, loadingConfig = _a.loadingConfig, themeCss = _a.themeCss, id = _a.id, env = _a.env, ns = _a.classPrefix;
        var body = [];
        if (options && options.length) {
            body = options.map(function (option, key) { return _this.renderItem(option, key); });
        }
        if (checkAll && body.length && optionType === 'default') {
            body.unshift(React.createElement(Checkbox, { key: "checkall", className: itemClassName, onChange: onToggleAll, checked: !!selectedOptions.length, partial: inRange(selectedOptions.length, 0, flattenTreeWithLeafNodes(options).length), disabled: disabled, inline: inline, labelClassName: labelClassName }, checkAllText !== null && checkAllText !== void 0 ? checkAllText : __('Checkboxes.selectAll')));
        }
        body = this.columnsSplit(body);
        var css = formateCheckThemeCss(themeCss, 'checkboxes');
        return (React.createElement("div", { className: cx("CheckboxesControl", className, setThemeClassName(__assign(__assign({}, this.props), { name: [
                    'checkboxesControlClassName',
                    'checkboxesControlCheckedClassName',
                    'checkboxesClassName',
                    'checkboxesCheckedClassName',
                    'checkboxesInnerClassName',
                    'checkboxesShowClassName'
                ], id: id, themeCss: css }))), ref: this.checkboxRef },
            body && body.length ? (body) : loading ? null : (React.createElement("span", { className: "Form-placeholder" }, __(placeholder))),
            loading ? (React.createElement(Spinner, { show: true, icon: "reload", size: "sm", spinnerClassName: cx('Checkboxes-spinner'), loadingConfig: loadingConfig })) : null,
            (creatable || addApi) && !disabled ? (React.createElement("a", { className: cx('Checkboxes-addBtn'), onClick: this.handleAddClick },
                React.createElement(Icon, { icon: "plus", className: "icon" }),
                __(createBtnLabel))) : null,
            React.createElement(CustomStyle, __assign({}, this.props, { config: {
                    themeCss: css,
                    classNames: [
                        {
                            key: 'checkboxesControlClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox:not(.checked):not(.disabled)")
                                },
                                hover: {
                                    suf: " .".concat(ns, "Checkbox:not(.disabled):not(.checked)")
                                },
                                disabled: {
                                    inner: ".".concat(ns, "Checkbox.disabled:not(.checked)")
                                }
                            }
                        },
                        {
                            key: 'checkboxesControlCheckedClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox.checked:not(.disabled)")
                                },
                                hover: {
                                    suf: " .".concat(ns, "Checkbox.checked:not(.disabled)")
                                },
                                disabled: {
                                    inner: ".".concat(ns, "Checkbox.checked.disabled")
                                }
                            }
                        },
                        {
                            key: 'checkboxesClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox:not(.checked):not(.disabled) > i")
                                },
                                hover: {
                                    suf: " .".concat(ns, "Checkbox:not(.disabled):not(.checked)"),
                                    inner: '> i'
                                },
                                disabled: {
                                    inner: ".".concat(ns, "Checkbox.disabled:not(.checked) > i")
                                }
                            }
                        },
                        {
                            key: 'checkboxesCheckedClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox:not(.disabled) > i")
                                },
                                hover: {
                                    suf: " .".concat(ns, "Checkbox:not(.disabled)"),
                                    inner: '> i'
                                },
                                disabled: {
                                    inner: ".".concat(ns, "Checkbox.disabled > i")
                                }
                            }
                        },
                        {
                            key: 'checkboxesInnerClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox:not(.disabled) > i .icon")
                                },
                                hover: {
                                    suf: " .".concat(ns, "Checkbox:not(.disabled)"),
                                    inner: '> i .icon'
                                },
                                disabled: {
                                    inner: ".".concat(ns, "Checkbox.disabled > i .icon")
                                }
                            }
                        },
                        {
                            key: 'checkboxesShowClassName',
                            weights: {
                                default: {
                                    inner: ".".concat(ns, "Checkbox > i")
                                }
                            }
                        }
                    ],
                    id: id
                }, env: env }))));
    };
    CheckboxesControl.defaultProps = {
        columnsCount: 1,
        multiple: true,
        placeholder: 'placeholder.noOption',
        creatable: false,
        inline: true,
        createBtnLabel: 'Select.createLabel',
        optionType: 'default'
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "handleAddClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "handleEditClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Event, Object]),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "handleDeleteClick", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "updateBorderStyle", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "addChildRefs", null);
    __decorate([
        supportStatic(),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], CheckboxesControl.prototype, "render", null);
    return CheckboxesControl;
}(React.Component));
var CheckboxesControlRenderer = /** @class */ (function (_super) {
    __extends(CheckboxesControlRenderer, _super);
    function CheckboxesControlRenderer() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CheckboxesControlRenderer = __decorate([
        OptionsControl({
            type: 'checkboxes',
            sizeMutable: false,
            thin: true
        })
    ], CheckboxesControlRenderer);
    return CheckboxesControlRenderer;
}(CheckboxesControl));

export { CheckboxesControlRenderer, CheckboxesControl as default };
